<template>
  <div class="route-history-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title-bold">航线变更历史</span>
          <div class="search-bar">
            <el-select
              v-model="searchType"
              placeholder="搜索类型"
              style="width: 120px; margin-right: 10px"
            >
              <el-option label="航班号" value="flightNumber" />
              <el-option label="新始发地" value="newDeparture" />
              <el-option label="新目的地" value="newDestination" />
              <el-option label="新经停站" value="newStopover" />
            </el-select>

            <el-input
              v-model="searchQuery"
              :placeholder="getPlaceholder()"
              style="width: 200px; margin-right: 10px"
              clearable
              @keyup.enter="fetchRouteHistories"
            />
            <el-button type="primary" @click="fetchRouteHistories">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="routeHistories"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="flightNumber" label="航班号" min-width="120" align="center" />
        <el-table-column label="原航线" align="center">
          <el-table-column prop="oldDeparture" label="始发站" min-width="120" align="center" />
          <el-table-column label="经停站" align="center">
            <template #default="{ row }">
              {{ row.oldStopovers && row.oldStopovers.length > 0 ? row.oldStopovers.join(', ') : '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="oldDestination" label="终点站" min-width="120" align="center" />
        </el-table-column>
        <el-table-column label="新航线" align="center">
          <el-table-column prop="newDeparture" label="始发站" min-width="120" align="center" />
          <el-table-column label="经停站" align="center">
            <template #default="{ row }">
              {{ row.newStopovers && row.newStopovers.length > 0 ? row.newStopovers.join(', ') : '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="newDestination" label="终点站" min-width="120" align="center" />
        </el-table-column>
        <el-table-column prop="updateTime" label="变更时间" min-width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="approvalStatus" label="审核状态" min-width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.approvalStatus)">
              {{ row.approvalStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updatedBy" label="操作" min-width="150" align="center" v-if="userRole === 'admin'">
          <template #default="{ row }">
            <div>
              <template v-if="row.updatedBy === 'SYSDBA'">
                <el-button
                  type="primary"
                  size="small"
                  @click="showApproveDialog(row)"
                >
                  审批
                </el-button>
              </template>
              <template v-else>
                <span>{{ row.updatedBy }}</span>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 15, 20, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.totalRecords"
        />
      </div>
    </el-card>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approveDialogVisible"
      :title="`航班 ${currentApproveItem?.flightNumber || ''} 审批`"
      width="500px"
      class="form-dialog"
    >
      <el-form :model="currentApproveItem" label-width="100px">
        <el-form-item label="航班号">
          <el-input v-model="currentApproveItem.flightNumber" disabled />
        </el-form-item>
        <el-form-item label="变更时间">
          <el-input v-model="currentApproveItem.updateTime" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitApproval(true)"
            class="dialog-btn confirm-btn"
          >
            通过
          </el-button>
          <el-button
            type="danger"
            @click="submitApproval(false)"
            class="dialog-btn reject-btn"
          >
            拒绝
          </el-button>
          <el-button @click="approveDialogVisible = false" class="dialog-btn cancel-btn">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { FlightApi } from '@/api/flight'
import { useStore } from 'vuex'
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'RouteHistoryView',
  setup () {
    const store = useStore()
    const userRole = computed(() => store.state.user?.role || 'user')
    return { userRole }
  },
  data () {
    return {
      routeHistories: [],
      loading: false,
      searchType: 'flightNumber',
      searchQuery: '',
      pagination: {
        currentPage: 1,
        pageSize: 10,
        totalRecords: 0
      },
      approveDialogVisible: false,
      currentApproveItem: null,
      approvalType: null
    }
  },
  created () {
    this.fetchRouteHistories()
  },
  methods: {
    getPlaceholder () {
      switch (this.searchType) {
        case 'flightNumber': return '请输入航班号'
        case 'newDeparture': return '请输入新始发地'
        case 'newDestination': return '请输入新目的地'
        case 'newStopover': return '请输入新经停站'
        default: return '请输入搜索内容'
      }
    },

    resetSearch () {
      this.searchType = 'flightNumber'
      this.searchQuery = ''
      this.pagination.currentPage = 1
      this.fetchRouteHistories()
    },

    async fetchRouteHistories () {
      this.loading = true
      try {
        const { currentPage, pageSize } = this.pagination
        let response

        if (this.searchQuery.trim()) {
          switch (this.searchType) {
            case 'flightNumber':
              response = await FlightApi.getRouteHistoriesByFlightNumber(
                this.searchQuery,
                currentPage,
                pageSize
              )
              break
            case 'newDeparture':
              response = await FlightApi.getRouteHistoriesByNewDeparture(
                this.searchQuery,
                currentPage,
                pageSize
              )
              break
            case 'newDestination':
              response = await FlightApi.getRouteHistoriesByNewDestination(
                this.searchQuery,
                currentPage,
                pageSize
              )
              break
            case 'newStopover':
              response = await FlightApi.getRouteHistoriesByNewStopover(
                this.searchQuery,
                currentPage,
                pageSize
              )
              break
          }
        } else {
          response = await FlightApi.getAllRouteHistories(currentPage, pageSize)
        }

        if (response && response.data) {
          this.routeHistories = response.data || []
          this.pagination.totalRecords = response.totalRecords || 0
        }
      } catch (error) {
        console.error('获取航线变更历史失败:', error)
        this.$message.error('获取航线变更历史失败')
      } finally {
        this.loading = false
      }
    },

    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.fetchRouteHistories()
    },

    handleCurrentChange (val) {
      this.pagination.currentPage = val
      this.fetchRouteHistories()
    },

    formatDateTime (dateTime) {
      if (!dateTime) return ''
      try {
        const date = new Date(dateTime)
        return date.toLocaleString()
      } catch (e) {
        return dateTime
      }
    },

    getStatusTagType (status) {
      switch (status) {
        case 'APPROVED':
          return 'success'
        case 'PENDING':
          return 'warning'
        case 'REJECTED':
          return 'danger'
        default:
          return 'info'
      }
    },

    showApproveDialog (row) {
      this.currentApproveItem = row
      this.approveDialogVisible = true
    },

    async submitApproval (isApproved) { // 接收参数
      if (!this.currentApproveItem) return

      try {
        let url
        let message
        if (isApproved) { // 使用传入的参数
          url = 'http://localhost:8081/flightUpdate/approveAirlChange'
          message = '审核通过并更新成功'
        } else {
          url = 'http://localhost:8081/flightUpdate/rejectAirlChange'
          message = '审核不通过'
        }

        await axios.post(url, null, {
          params: {
            dfltFlid: this.currentApproveItem.flightNumber,
            recipientEmail: '1019399421@qq.com'
          }
        })

        ElMessage.success(message)
        this.approveDialogVisible = false
        this.fetchRouteHistories()
      } catch (error) {
        console.error('审核失败:', error)
        ElMessage.error('审核失败: ' + (error.message || '未知错误'))
      }
    }
  }
}
</script>

<style scoped>
.title-bold {
  font-weight: bold;
  font-size: 18px;
}

.route-history-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}

.el-button--success {
  margin-left: 5px;
}

.form-dialog .el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #606266;
}
</style>
